package com.rainliang.project.connect.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.rainliang.project.user.basic.bean.RegistBean;



/**
 * @author 
 * 	oauth2.0接口
 *	由于专题的微博加关注没有支持1.0的接口，所以升到oauth2.0	
 *	access token，此参数在访问用户授权信息中会用到。
 *	access token由每次用户登录时生成，过期时间默认为三个月，用户再次登录时自动刷新，请网站做好防过期策略，或过期后提示用户再次授权。
 *
 * 发新鲜事建议网站将请求的频率限制在每秒1次以下
 */
public class QQ_Util {
	public static String TXQQ_COOKIE_DATA_KEY="myuu-txqq";
	public static String appid="100329634";
	public static String appkey="44909d1228436850b55e7429670e6a00";

	public static final String scope="get_info,get_user_info,add_share,add_t,add_pic_t,add_idol";
	private static Log logger = LogFactory.getLog(QQ_Util.class);
	
	public final static Integer down = 0;
	public final static Integer favorate = 1;
	public final static Integer up = 2;
	public final static Integer message = 3;
	public final static Integer doudan_fav = 4;
	public final static Integer doudan_top = 5;
	public final static String[] dongzuo = { "下载", "收藏了", "顶了", "评论了", "收藏了豆单","顶了豆单" };
	
	
	/***********************************************************QQ升级登录接口OAUTH2.0****************************************************************************/
	/**
	 * 获取accesstoken 升级oauth2.0用
	 * @param authorization_Code 授权第一步获得的authorization_Code
	 * @param redirect_uri 回调地址和初次请求的回调地址保持一致
	 * @return
	 */
	public static Map<String,String> getAccessToken(String authorization_Code,String redirect_uri){
		if(authorization_Code==null)return null;
		Map<String,String> map=new HashMap<String, String>();
		String url="https://graph.qq.com/oauth2.0/token";
		String accessToken=null;
		try{
			HttpClient client=new HttpClient();			
			String geturl=url+"?grant_type=authorization_code&code="+authorization_Code+"&client_id="+appid+"&client_secret="+appkey+"&redirect_uri="+redirect_uri+"&state=docin";
			GetMethod method=new GetMethod(geturl);
			method.getParams().setParameter("http.socket.timeout",new Integer(10000));
			client.executeMethod(method);
			String resultStr=method.getResponseBodyAsString();
			method.releaseConnection();
			
			if(resultStr!=null&&resultStr.contains("access_token")){
				String accessTokenTmpStr=resultStr.substring(0, resultStr.indexOf("&"));
				String expireTmpStr=resultStr.substring(resultStr.indexOf("&")+1);
				if(accessTokenTmpStr!=null){
					String []tmpArray=accessTokenTmpStr.split("=");
					if(tmpArray!=null&&tmpArray.length==2){
						accessToken=tmpArray[1];
						map.put("accessToken", accessToken);
					}
				}
			}else if(resultStr!=null){
				logger.error("------------QQ2.0----getAccessToken-error--backstr:"+resultStr);
//				Pattern p = Pattern.compile("\\(.*?\\)");
//				Matcher m = p.matcher(resultStr);
//				if(m.find()){
//					resultStr=m.group();
//				}
//				resultStr=resultStr.substring(1, resultStr.length()-1);
//				JSONObject json=JSONObject.fromObject(resultStr);
//				if(json!=null&&json.has("error")){
//					String error=json.getString("error");
//					String error_des=json.getString("error_description");
//					if(error!=null){
//						logger.warn("-----------QQ getAccessToken error,errorCode:"+error+",error_des:"+error_des);
//					}
//				}else{
//					logger.warn("error:QQ get jsonobject error!");
//				}
			}
		}catch(Exception e){
			logger.warn("getAccessToken error:authorization_Code:"+authorization_Code+";redirect_uri:"+redirect_uri, e);
		}		
		return map;
	}
	/**
	 * 获取用户的openid 升级oauth2.0用
	 * @param accesstoken
	 * @return
	 */
	public static String getOpenId(String accesstoken){
		if(accesstoken==null||accesstoken.equals(""))return null;
		String url="https://graph.qq.com/oauth2.0/me";
		String openId=null;
		try{
			HttpClient client=new HttpClient();			
			String geturl=url+"?access_token="+accesstoken;
			GetMethod method=new GetMethod(geturl);
			method.getParams().setParameter("http.socket.timeout",new Integer(10000));
			client.executeMethod(method);
			String resultStr=method.getResponseBodyAsString();
			method.releaseConnection();
			
			if(resultStr!=null&&!resultStr.equals("")){
				Pattern p = Pattern.compile("\\(.*?\\)");//返回格式为：callback(json数据);使用正则获取圆括号内的内容
				Matcher m = p.matcher(resultStr);
				if(m.find()){
					resultStr=m.group();
					resultStr=resultStr.substring(1, resultStr.length()-1);
					JSONObject json=JSONObject.fromObject(resultStr);
					if(json!=null&&json.has("openid")){
						openId=json.getString("openid");
						String client_id=json.getString("client_id");
//					logger.warn("--------------openid="+openId+",client_id="+client_id);
					}else if(json!=null&&json.has("error")){
						String error=json.getString("error");
						String error_des=json.getString("error_description");
						if(error!=null){
							logger.warn("-----------QQ openid error,errorCode:"+error+",error_des:"+error_des);
						}
					}else{
						logger.warn("error:QQ openid get   jsonobject error!");
					}
				}else{
					logger.warn("error:QQ1.0 getOpenId resultStr="+resultStr);
				}
			}
		}catch(Exception e){
			logger.warn("getOpenId error", e);
		}		
		return openId;
	}
	/**
	 * 获取用户信息 升级oauth2.0用(空间)
	 * @param oauth_token_access
	 * @param openid
	 * @return
	 */
	public static RegistBean getUserInfo_v2(String oauth_token_access,String openid){
		String userInfo = "";
		RegistBean regBean = null;
		try {
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);  
			client.getHttpConnectionManager().getParams().setSoTimeout(10000);
			String url = "https://graph.qq.com/user/get_user_info";
			
			String geturl = url + "?access_token=" + oauth_token_access+"&oauth_consumer_key="+appid+"&openid="+openid+"&format=json";
			GetMethod method = new GetMethod(geturl);
			method.getParams().setParameter("http.socket.timeout",new Integer(20000));
			method.addRequestHeader("Content-Type", "text/html");
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			client.executeMethod(method);
			userInfo = method.getResponseBodyAsString();
			method.releaseConnection();
			
			JSONObject json = JSONObject.fromObject(userInfo);
			if (json != null) {
				if(json.has("ret")&&json.getString("ret").equals("0")){
					regBean = new RegistBean();
					String namestr=(String) json.get("nickname");
					if(namestr==null)namestr="";
					int end=namestr.trim().length();
					end=end>70?70:end;
					regBean.setNickName(namestr.trim().substring(0, end));
					regBean.setAvatar((String) json.get("figureurl_2"));					
				}else if(json.has("ret")&&!json.getString("ret").equals("0")){
					String ret=json.getString("ret");
					String msg=json.getString("msg");
					logger.warn("get userinfo error,retCode:"+ret+",msg:"+msg);
				}
			}
		} catch (Exception e) {
			logger.warn("getUserInfo_v2  error oauth_token_access:"+oauth_token_access+";openid:"+openid+",resultStr="+userInfo, e);
			regBean = null;
		}
		return regBean;
	}
	
	public static int getWBFansV2(String oauth_token_access,String openid){
		int wbFansNum=0;
		try {
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);  
			client.getHttpConnectionManager().getParams().setSoTimeout(3000);
			String url = "https://graph.qq.com/user/get_info";
			
			String geturl = url + "?access_token=" + oauth_token_access+"&oauth_consumer_key="+appid+"&openid="+openid+"&format=json";
			GetMethod method = new GetMethod(geturl);
			method.getParams().setParameter("http.socket.timeout",new Integer(20000));
			method.addRequestHeader("Content-Type", "text/html");
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
			client.executeMethod(method);
			String userInfo = method.getResponseBodyAsString();
			method.releaseConnection();
			
			JSONObject json = JSONObject.fromObject(userInfo);
			if (json != null&&json.has("data")) {
				JSONObject user = json.getJSONObject("data");
				if (user != null && user.has("fansnum")) {
					wbFansNum = user.getInt("fansnum");
				} else {
					logger.warn("get wb userinfo data error ,msg="+userInfo);
				}
			}else{
				logger.warn("get wb userinfo error ,msg="+userInfo);
			}
		} catch (Exception e) {
			logger.warn("getuserinfo  error", e);
			return 0;
		}
		return wbFansNum;
	}
	/**
	 * @param ps 文档bean
	 * @param type 发送新鲜事的类型
	 * @param firstPid 豆单的第一篇文档id
	 * @param msg 评论的内容
	 * @param request HttpServletRequest
	 * @return 1发送成功,0发送失败,-1获取UserInfo_Home失败,-2用户设置过新鲜事,不允许发送新鲜事,-3获取用户accessToken或openid失败,-4参数ps为null
	 */
	/*public static int add_sharev2(ProductBean_State ps,Integer type, Long firstPid, String msg, UserInfo_Home userInfo_Home){
		if(userInfo_Home==null)return -1;
		int txqqNews=userInfo_Home.getTxqq_news();
		String accessToken=userInfo_Home.getTxqq_oauth_token();
		String openid=userInfo_Home.getTxqq_uid();
		if(accessToken==null||accessToken.equals("")||openid==null||openid.equals("")){
			logger.warn("-----user:"+userInfo_Home.getUser_id()+" accessToken is: "+accessToken+",openid is: "+openid);
			return -3;
		}
		if(ps==null)return -4;
		if (txqqNews != 0 && QQ_Util.if_send_feed(txqqNews, type)) {
			String title=null;
			String url=null;
			String comment="";
			String images="";
			String summary="";
			
			if (firstPid == null) {//文档的新鲜事
				title = ps.getProductName();
				url = "http://www.docin.com/p-"+ps.getProductId()+".html?nb="+RenRenUtil.CONN_USER_TYPE[1];
				comment =(type == QQ_Util.message)?msg:"";
				summary = ps.getProductDesc() == null ? ps.getProductName(): ps.getProductDesc();
				images = ImageUtil.getProductPic(ps.getProductId(),"110x140");
			}else {//豆单的新鲜事
				title = ps.getProductName();
				url = "http://www.docin.com/d-" + ps.getProductId()+ ".html?nb="+RenRenUtil.CONN_USER_TYPE[1];
				summary = ps.getProductDesc() == null ? ps.getProductName(): ps.getProductDesc();
				if(ps.getPreviewPath() == null || "".equals(ps.getPreviewPath())){
					images = ImageUtil.getProductPic(firstPid, "110x140");
				}else{
					images = ImageUtil.getProductPic(ps.getProductId(),"110x140");
				}
			}
			
			int flag=QQ_Util.addshareV2(accessToken, openid, title, url, comment, summary, images);
			//logger.warn("-------------QQ add_sharev2-------["+openid+"],["+title+"]");
			if(flag==1){
				//logger.warn("-------------QQ add_sharev2-- 1, 0, 2, 1, 0-----");
				VstateUtil.sendFeed_Operate(1, 0, 2, 1, 0);//QQ发送新鲜事统计放Queue
				return 1;
			}
		}else{
			return -2;
		}
		return 0;
	}*/

	/**
	 * 在用户授权的情况下，可以以用户的名义发布一条动态（feeds）到QQ空间和朋友网上，此外还可在腾讯微博上发一条微博
	 * @param access_token
	 * @param openid
	 * @param title
	 * @param backurl
	 * @param comment
	 * @param summary
	 * @param images
	 * @return	-1参数错误,0发送失败,1发送成功
	 */
	public static int addshareV2(String access_token,String openid,String title, String backurl,String comment,String summary,String images) {
//		logger.warn("title:"+title+"\nurl:"+backurl+"\ncomment:"+comment+"\nsummary:"+summary+"\nimages="+images);
		String add_share_url="https://graph.qq.com/share/add_share";
		try {
			if (access_token == null || access_token.isEmpty()) {
				logger.error("addshare access_token == null || access_token.isEmpty()");
				return -1;
			}
			if (openid == null || openid.equals("")) {
				logger.error("-addshare！openid == null || openid.equals");
				return -1;
			} 
			if(title==null||backurl==null){
				logger.error("-addshare title==null||url==null");
				return -1;
			}
			URL url = new URL(add_share_url);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			conn.setRequestMethod("POST"); 
			StringBuffer sb=new StringBuffer();
			sb.append("access_token="+access_token);
			sb.append("&oauth_consumer_key="+appid);
			sb.append("&openid="+openid);
			sb.append("&title="+URLEncoder.encode(title,"utf-8"));
			sb.append("&url="+URLEncoder.encode(backurl,"utf-8"));
			sb.append("&comment="+comment);
			sb.append("&summary="+URLEncoder.encode(summary,"utf-8"));
			sb.append("&images="+URLEncoder.encode(images,"utf-8"));
			sb.append("&format=json");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			OutputStream os = conn.getOutputStream();
			os.write(sb.toString().getBytes("utf-8")); 
			os.close();  
			
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
			String line ; 
			String result =""; 
			while((line =br.readLine())!= null ){ 
			       result += "\n"+line; 
			} 
//			logger.warn("result="+result);
			//处理返回结果
			JSONObject json=JSONObject.fromObject(result);
			if(json!=null){
				if(json.has("ret")){
					String ret=json.getString("ret");
					if(ret.equals("0")){
						return 1;
					}else if("100014".equals(ret)){//token过期，在这里进行过期处理
						String msg=json.getString("msg");
						logger.warn("------------2.0 addshare error  token过期---------errorRet:"+ret+",msg:"+msg+",openid="+openid);
						
					}else{//发送失败 若3021:同一帐号连续分享了同一个URL。
						String msg=json.getString("msg");
						logger.warn("------------2.0 addshare error---------errorRet:"+ret+",msg:"+msg+",openid="+openid);
					}
				}else{
					logger.warn("2.0addshare to qzone error!,error_des:"+json.toString()+",openid="+openid);
				}
			}else{
				logger.warn("2.0addshare to qzone error!!"+result+",openid="+openid);
			}
			
		} catch (Exception e) {
			logger.error("---qq 2.0 同步消息---出错了！！！" + "  " + e.toString()+",openid="+openid);
		}
		return 0;
	}
	/**
	 * 发表腾讯微博
	 * @param access_token QQ用户对应的access_token
	 * @param openid QQ用户的OpenId
	 * @param content 微博内容
	 * @param clientip 客户端ip
	 * @param jing 用户所在地理位置的经度
	 * @param wei 用户所在地理位置的纬度
	 * @param image 发带图片的微博传入图片的url，格式如"http://www.docin.com/1.jpg",发不带图片的微博传入null或""
	 * @return true发表微博成功，false发表微博失败
	 */
	public static boolean sendTencentWBv2(String access_token,String openid,String content,String clientip,String jing,String wei,String image){
		if (access_token == null || access_token.isEmpty()) {
			logger.error("add_t  access_token == null || access_token.isEmpty()");
			return false;
		}
		if (openid == null || openid.equals("")) {
			logger.error("-add_t ！openid == null || openid.equals");
			return false;
		} 
		if(content==null||content.equals("")){
			logger.error("-add_t  content==null||content is empty");
			return false;
		}
		if(clientip==null){
			clientip="";
		}
		if(jing==null||wei==null){
			jing="";
			wei="";
		}
		
		if(image!=null&&!image.equals("")){
			return add_pic_t(access_token, openid, content, clientip, jing, wei, image)>0;
		}else{
			return add_t(access_token, openid, content, clientip, jing, wei)>0;
		}
	}
	
	/**
	 * 发表腾讯微博,不带图片
	 * @param access_token 
	 * @param openid 
	 * @param content 发表内容
	 * @param clientip 客户端ip
	 * @param jing 经度
	 * @param wei 纬度
	 * @return -1参数错误,0发送失败,1发送成功
	 */
	public static int add_t(String access_token,String openid,String content,String clientip,String jing,String wei) {
		
		String add_t_url="https://graph.qq.com/t/add_t";
		try {
			if (access_token == null || access_token.isEmpty()) {
				logger.error("add_t  access_token == null || access_token.isEmpty()");
				return -1;
			}
			if (openid == null || openid.equals("")) {
				logger.error("-add_t ！openid == null || openid.equals");
				return -1;
			} 
			if(content==null||content.equals("")){
				logger.error("-add_t  content==null||content is empty");
				return -1;
			}
			if(clientip==null){
				clientip="";
			}
			if(jing==null||wei==null){
				jing="";
				wei="";
			}
			
			URL url = new URL(add_t_url);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			conn.setRequestMethod("POST"); 
			StringBuffer sb=new StringBuffer();
			sb.append("access_token="+access_token);
			sb.append("&oauth_consumer_key="+appid);
			sb.append("&openid="+openid);
			sb.append("&content="+URLEncoder.encode(content,"utf-8"));
			sb.append("&clientip="+clientip);
			sb.append("&jing="+jing);
			sb.append("&wei ="+wei);
			sb.append("&format=json");
			
			conn.setDoInput(true);
			conn.setDoOutput(true);
			OutputStream os = conn.getOutputStream();
			os.write(sb.toString().getBytes("utf-8")); 
			os.close();  
			
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
			String line ; 
			String result =""; 
			while((line =br.readLine())!= null ){ 
			       result += "\n"+line; 
			} 
			//处理返回结果
			JSONObject json=JSONObject.fromObject(result);
			if(json!=null){
				if(json.has("ret")){
					String ret=json.getString("ret");
					if(ret.equals("0")){
						return 1;
					}else if("100014".equals(ret)){//token过期，在这里进行过期处理
						String msg=json.getString("msg");
						logger.warn("------------2.0 add_t error---------errorRet:"+ret+",msg:"+msg);
					}else{//发送失败
						String msg=json.getString("msg");
						logger.warn("------------2.0 add_t error---------errorRet:"+ret+",msg:"+msg);
					}
				}else{
					logger.warn("2.0 add_t error!,error_des:"+json.toString());
				}
			}else{
				logger.warn("2.0 add_t error!!"+result);
			}
			
		} catch (Exception e) {
			logger.error("---qq2.0发表微博---出错了！！！" + "  " + e.getMessage());
		}
		return 0;
	}
	/**
	 * 发表腾讯微博，带图片
	 * @param access_token
	 * @param openid
	 * @param content 发表内容
	 * @param clientip 客户端ip
	 * @param jing 经度
	 * @param wei 纬度
	 * @param imageurl 图片url
	 * @return
	 */
	public static int add_pic_t(String access_token,String openid,String content,String clientip,String jing,String wei,String imageurl) {
		
		String add_t_url="https://graph.qq.com/t/add_pic_t";
		try {
			/*****************************参数判断******************************************/
			if (access_token == null || access_token.isEmpty()) {
				logger.error("add_t  access_token == null || access_token.isEmpty()");
				return -1;
			}
			if (openid == null || openid.equals("")) {
				logger.error("-add_t ！openid == null || openid.equals");
				return -1;
			} 
			if(content==null||content.equals("")){
				logger.error("-add_t  content==null||content is empty");
				return -1;
			}
			if(imageurl==null||imageurl.equals("")){
				logger.error("--- imageurl ==null or imageurl is empty");
				return -1;
			}
			if(clientip==null){
				clientip="";
			}
			if(jing==null||wei==null){
				jing="";
				wei="";
			}
			/*****************************获取图片二进制流*开始**************************************************/
			URL imgurl=new URL(imageurl);
            URLConnection uc=imgurl.openConnection(); 
            InputStream is=uc.getInputStream(); 
			byte[] b=new byte[1024];
			int len;
			byte[] total=new byte[0];
			while ((len = is.read(b)) != -1) {
				byte[] dest = new byte[total.length + len];  
			    System.arraycopy(total, 0, dest, 0, total.length); 
			    System.arraycopy(b, 0, dest, total.length, len); 
				total=dest;
			}
			is.close();
			/*******************************获取图片二进制流*结束*************************************************/
			String[] props ={"access_token","oauth_consumer_key","openid","content","clientip","jing","wei","format"}; // 字段名 
			String[] values ={access_token,appid,openid,content,clientip,jing,wei,"json"};// 字段值 
			byte[] file = total; // 文件内容 
			String BOUNDARY = "c9152e99a2d6487fb0bfd02adec3aa16"; // 分隔符 
			StringBuffer sb = new StringBuffer(); 
			String imgname=imageurl.substring(imageurl.lastIndexOf(".")+1);
			if(imgname==null||imageurl.equals("")){
				imgname="pic.jpeg";
			}else{
				imgname="pic"+imgname;
			}
			for (int i = 0; i < props.length; i++) {
				sb = sb.append("--"); 
				sb = sb.append(BOUNDARY); 
				sb = sb.append("\r\n"); 
				sb = sb.append("Content-Disposition: form-data; name=\""+ props[i] + "\"\r\n\r\n"); 
				sb = sb.append(values[i]); 
				sb = sb.append("\r\n"); 
			}
			/******************图片***********************/
			sb = sb.append("--"); 
			sb = sb.append(BOUNDARY); 
			sb = sb.append("\r\n"); 
			sb = sb.append("Content-Disposition: form-data; name=\"pic\"; filename=\""+imgname+"\"\r\n"); 
			sb = sb.append("Content-Type: image/jpeg\r\n\r\n"); 
			
			byte[] data = sb.toString().getBytes("UTF-8"); 
			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 
			
			URL url = new URL(add_t_url);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(10000);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); 
			conn.setRequestProperty("Content-Length", String.valueOf(data.length + file.length + end_data.length));
			conn.setDoOutput(true);
			conn.setDoInput(true);
			OutputStream os = conn.getOutputStream();
			os.write(data);//写入字段参数
			os.write(file);//写入图片字节流
			os.write(end_data);//写入结束标志
			os.close();  
			/******************发送微博结束***********************/
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
			String line ; 
			String result =""; 
			while((line =br.readLine())!= null ){ 
			       result += "\n"+line; 
			} 
			//logger.warn(""+result);
			//处理返回结果
			JSONObject json=JSONObject.fromObject(result);
			if(json!=null){
				if(json.has("ret")){
					String ret=json.getString("ret");
					if(ret.equals("0")){
						return 1;
					}else if("100014".equals(ret)){//token过期，在这里进行过期处理
						String msg=json.getString("msg");
						logger.warn("------------2.0 add_t error---------errorRet:"+ret+",msg:"+msg);
					}else{//发送失败
						String msg=json.getString("msg");
						String errcode=json.getString("errcode");
						logger.warn("------------2.0 add_t error---------errorRet:"+ret+",msg:"+msg+",二级错误码："+errcode);
					}
				}else{
					logger.warn("2.0 add_t error!,error_des:"+json.toString());
				}
			}else{
				logger.warn("2.0 add_t error!!"+result);
			}
			
		} catch (Exception e) {
			logger.error("---qq发表微博---出错了！！！" + "  " + e.getMessage());
		}
		return 0;
	}
	/***********************************************oauth2.0接口升级结束************************************************************/
	
	/*public static void testfans(String oauth_token_secret,String oauth_access_token, String openid,String content, String img) throws HttpException, IOException {
		//参数验证
		//构造参数
		String url = "http://openapi.qzone.qq.com/relation/add_idol";
		int oauth_nonce = new Random().nextInt(9876599) + 123400;
		long oauth_timestamp = System.currentTimeMillis() / 1000;
		String oauth_version = "1.0";
		String oauth_signature_method = "HMAC-SHA1";
		
		List<String> list = new ArrayList<String>();
		list.add("oauth_consumer_key=" +QQ_Util.appid);
		list.add("oauth_token=" + oauth_access_token);
		list.add("oauth_nonce=" + oauth_nonce);
		list.add("oauth_timestamp=" + oauth_timestamp);
		list.add("oauth_version=" + oauth_version);
		list.add("oauth_signature_method=" + oauth_signature_method);
		list.add("openid=" + openid);
		list.add("format=" + "json");
//		list.add("name=docin_chuangye");
		list.add("fopenids=112C3360BF9717F8F50F842F2BAD7046");

		String oauth_signature = getSignature(list, url, oauth_token_secret);
		
		NameValuePair[] data = {
				new NameValuePair("oauth_consumer_key", QQ_Util.appid),
				new NameValuePair("oauth_token", oauth_access_token),
				new NameValuePair("oauth_nonce", oauth_nonce + ""),
				new NameValuePair("oauth_timestamp", oauth_timestamp + ""),
				new NameValuePair("oauth_version", oauth_version),
				new NameValuePair("oauth_signature_method",oauth_signature_method),
				new NameValuePair("openid", openid),
				new NameValuePair("format", "json"),
//				new NameValuePair("name","docin_chuangye"),
				new NameValuePair("oauth_signature", oauth_signature),
				new NameValuePair("fopenids", "112C3360BF9717F8F50F842F2BAD7046")};

		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);  
		client.getHttpConnectionManager().getParams().setSoTimeout(3000);
		PostMethod method = new UTF8PostMethod(url);
		 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,   
				   new DefaultHttpMethodRetryHandler());   

		method.setRequestBody(data);
		client.executeMethod(method);
		String response = method.getResponseBodyAsString();
		logger.warn(response.toString());
//		JSONObject json = JSONObject.fromObject(response);
//		String returnStr="";
//		if (json != null) {
//			if(json.has("ret")){
//				String ret=json.getString("ret")==null?"":json.getString("ret");
//				if(ret!=null&&ret.trim().equals("0")){
//					if(json.has("id")){
//						String id=json.getString("id");
//						String time=json.getString("time");
//						returnStr=id;
//						logger.warn("info:发送微博到腾讯成功！id="+id+",time="+time);
//					}					
//				}else{
//					if(json.has("msg")){
//						String msg=json.getString("msg");
//						returnStr=URLDecoder.decode(msg,"UTF-8");
//						logger.warn("error:发送微博到腾讯出错 msg="+returnStr+"&ret="+ret);
//					}	
//				}
//			}else{
//				logger.warn("error:发送微博到腾讯失败！no ret");
//			}
//		} else {
//			logger.warn("error:发送微博到腾讯失败！");
//		}  
//		return returnStr;
//		
	}*/
	/**
	 * 使用HttpConnection发送请求
	 * @param url请求地址
	 * @param param请求参数
	 * @param requestType请求类型，post,get；默认为post
	 * @return
	 */
	public static String sendRequest(String url,String param,String requestType){
		
		String data=null;
	    try {
	     URL dataUrl = new URL(url);//根据url创建一个URL的实例
	     HttpURLConnection con = (HttpURLConnection) dataUrl.openConnection();//根据URL实例创建一个connection实例
	     if(requestType!=null&&"get".equalsIgnoreCase(requestType)){
	    	 con.setRequestMethod(requestType.toUpperCase());//设置请求类型
	     }else{
	    	 con.setRequestMethod("POST");//设置请求类型
	     }
	     con.setRequestProperty("Proxy-Connection", "Keep-Alive");//设置代理
	     con.setDoOutput(true);//设置可以输出 
	     con.setDoInput(true);//设置可以输入

	     OutputStream os=con.getOutputStream();//返回一个输出流给该连接
	     DataOutputStream dos=new DataOutputStream(os);//创建一个数据输出流
	     dos.write(param.getBytes());//将请求所用的参数放入
	     dos.flush();
	     dos.close();

	     InputStream is=con.getInputStream();//返回一个输入流从连接
	     DataInputStream dis=new DataInputStream(is);//根据输入流对象创建数据输入流对象
	     byte d[]=new byte[dis.available()];
	     dis.read(d);
	     data=new String(d);
	    } catch (Exception ex) {
	    	logger.warn("sendRequest:"+ex);
	    }
		return data;
	}
}